import axios from 'axios'
import cookie from 'js-cookie'
import { MessageBox, Message } from 'element-ui'
// 创建axios实例
const service = axios.create({
  baseURL: 'http://101.37.77.12:9090', // api的base_url
  timeout: 20000 // 请求超时时间
})


//第三步 创建拦截器  http request 拦截器
service.interceptors.request.use(
  config => {
    //debugger
    if (cookie.get('token')) {
      config.headers['token'] = cookie.get('token');
    }
    return config
  },
  err => {
    return Promise.reject(err);
  })
// http response 拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code != 200) {
      //debugger
      if (response.data.code == 401) {
        // 返回 错误代码-1 清除ticket信息并跳转到登录页面
        //debugger
        window.location.href = "/login"
        return
      } else {
        Message({
          message: response.data.msg,
          type: 'error',
          duration: 5 * 1000
        })
        return
      } 
    }
    return response;
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error.response)   // 返回接口返回的错误信息
  });

export default service
